const xss = require('xss')
const { exec } = require('../db/mysql')

const getList = async (buyData = {}) => {
    const userId = xss(buyData.userId) 
    const finish = xss(buyData.finish) 	
    let sql = `select id,user_id,product_id,nums,date_format(createtime, '%Y-%m-%d %H:%i:%s') AS createtime,price,finish,name,factory,total from buys where user_id= '${userId}' ` 
   
	if (finish) {
        sql += `and finish = ${finish} `
    }
    sql += `order by createtime desc;`  
	
    return await exec(sql)
}

const getDetail = async (id) => {
    const sql = `select * from blogs where id='${id}'`
    const rows = await exec(sql)
    return rows[0]
}

const newBuy = async (buyData = {}) => {  
	const id = xss(buyData.id) 
    const userId = xss(buyData.userId) 
    const productId = xss(buyData.productId)  
    const nums = xss(buyData.nums)  
    const finish = xss(buyData.finish)  
    const price = xss(buyData.price)  
    const name = xss(buyData.name)    
    const factory = xss(buyData.factory)   
    const total = nums * price
	 
    const sql = `insert into buys (user_id, createtime,product_id,nums,finish,price,name,factory,total)
        values ('${userId}', now(), '${productId}', '${nums}', '${finish}', '${price}', '${name}', '${factory}', '${total}');`

    const insertData = await exec(sql)
    return {
        id: insertData.insertId
    }
}

const updateBuy = async (buyData = {}) => {  
    const id = xss(buyData.id)
    const finish = xss(buyData.finish) 
    const nums = xss(buyData.nums) 
    const total = xss(buyData.total) 
	let sql = `update buys set finish=${finish}`
	if(nums){
		sql += `,nums=${nums}`
	}
	if(total){
		sql += `,total=${total}`
	}
   sql += ` where id = ${id};`  
	
    const updateData = await exec(sql)
    if (updateData.affectedRows > 0) {
        return true
    }
    return false
}
 

module.exports = {
    getList,
    getDetail,
    newBuy,
    updateBuy, 
}